import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import { AtTag, AtButton, AtFloatLayout, AtTabs, AtTabsPane, AtList, AtListItem } from 'taro-ui'
import './doctorsession.scss'
import star from '../../img/star.png'
import right from '../../img/right.png'
import app from '../../main'

export default class Doctorsession extends Component {
    config = {
        navigationBarTitleText: ''
    }

    constructor() {
        super(...arguments)
        this.state = {
            coupons_id:'',
            current: 0,
            currents: 0,
            // floatlayout
            isOpen: false,

            // 医生数据和费用信息
            docInfo: {},
            //咨询记录内容
            charArr: [
            ],
            // 费用数据
            pay: {
                "patient_name": "",
                "totpalPrice": "",
                "coupons": [
                    {
                        "coupon_id": "1",
                        "title": "满100减10元",
                        "desc": null,
                        "coupon_type": "满减",
                        "use_type": "开始日期结束日期",
                        "start_time": "2019-05-16 14:26:17",
                        "end_time": "2019-08-20 14:10:48",
                        "days": "30",
                        "scope": "全订单可用",
                        "full_money": "100.00",
                        "discount": "10.00"
                    }
                ]
            },
            // 付多少钱
            payMoney: 0,
            // 优惠多少钱
            discountpay: 0,
            //标签是否显示
            ifshow:'',
            flag:true
        }
    }

    handleClicks(value) {
        this.setState({
            currents: value
        })
    }

    //立即咨询    
    gotoQuicklyFoundModify() {
        if(this.state.flag){
            let id  = this.state.docInfo.id
            var me = this;
            this.setState({
                flag:false
            })
            setTimeout(function(){
                me.setState({
                    flag:true
                })
            },10000)
            var data = {
                type: '专家咨询',
                doctor_id: id,
                health_archive_id: 0,
                inquiry_answer_id: 0,
                coupon_id:this.state.coupons_id
            };
            app.post('web/myself/mySubmitOrder', data, function(res) {
                if (res.data.status == 200) {
                    var result = res.data.result
                    let params = result.jsparams
                    console.log('返回参水',params)
                    app.wz_doctor_id = result.doctor_id;
                    app.wz_order_id = result.order_id;
                    console.log('-------1-------')
                    if(params == '' && me.state.payMoney <= 0){
                        console.log('-------2-------')
                        app.success('支付失败')
                        app.redirectTo('../quicklyFound/quicklyFound?state=支付跳转')
                    }else{
                        app.callPayment(params, function(res) {
                            console.log('-------3-------')
                            app.success('支付成功');
                            app.redirectTo('../quicklyFound/quicklyFound?state=支付跳转')
                        }, function(res) {
                            app.wz_doctor_id = '';
                            app.wz_order_id = '';
                            app.toastMessage('支付失败');
                        });
                    }
                } else {
                    app.toastMessage('提交订单失败');
                }
            });
        }
    }

    //跳转到周星星得咨询记录
    gotochatRecord(item) {
        app.navigateTo('../chatsub/pages/chatdetail/chatdetail'+'?relate_id='+item.relate_id+'&type='+item.type+'&receiver_id='+item.doctor_id)
    }

    openFloat() {
        if(this.state.pay.coupons.length == 0 || this.state.pay.coupons.length == undefined){
            app.alertTab('您还没拥有优惠券哦!')
        }else{
            this.setState({
                isOpen: true
            })
        }
    }
    // 优惠券过滤器
    counpfilter(arrary) {
        let result = []
        for (let i = 0; i < arrary.length; i++) {
            if (arrary[i].scope == "全订单可用") {
                result.push(arrary[i])
            }
        }
        return result
    }
    // 咨询费用数据计算
    youhui(discount,scope,type,id,fullMoney,start_time,end_time,e) {
        console.log('youhui',discount,scope,type,id,fullMoney,start_time,end_time,e)
        e.stopPropagation()
        let payNuber = Number(this.state.pay.totpalPrice) //应付非
        let discounts = 0//优惠
        if(scope !='全订单可用' && scope !='定向问诊'){
            Taro.showModal({
                title: '优惠券无法使用',
                content: '该优惠券无法在此使用',
                showCancel:false
              })
              return
        }
        if (Number(payNuber)<Number(fullMoney)){
            Taro.showModal({
              title: '优惠券无法使用',
              content: '使用条件不满足,需要满'+fullMoney+'元才可以使用!',
              showCancel:false
            })
            return
        }
        //校验日期
        var myDate = new Date();
        let now_time = myDate.toLocaleDateString()+" "+ myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds()
        now_time = now_time.replace("年","-","/").replace("月","-","/").replace("日","-"," "); 
        now_time = new Date(now_time.replace(/-/g, "/"))
        console.log(555,now_time)
        start_time = new Date(start_time.replace(/-/g, "/"));
        end_time = new Date(end_time.replace(/-/g, "/"));
        if(Date.parse(end_time) - Date.parse(now_time) < 0){
            Taro.showModal({
                title: '优惠券无法使用',
                content: '该优惠券已过期',
                showCancel:false
              })
            return
        }else if(Date.parse(start_time) - Date.parse(now_time) > 0){
            Taro.showModal({
                title: '优惠券无法使用',
                content: '该优惠券还未到使用日期',
                showCancel:false
              })
            return
        }

        if (type == "满减") {
            let arg1 = Number(payNuber)
            let arg2 = Number(discount)
            function accSubtr(arg1,arg2){
                var r1,r2,m,n;
                try{r1=arg1.toString().split(".")[1].length;}catch(e){r1=0;}
                try{r2=arg2.toString().split(".")[1].length;}catch(e){r2=0;}
                m=Math.pow(10,Math.max(r1,r2));
                //动态控制精度长度
                n=(r1>=r2)?r1:r2;
                return ((arg1*m-arg2*m)/m).toFixed(n);
            }
            payNuber = accSubtr(arg1,arg2)
            discounts = discount
            // payNuber = payNuber - discount
            // discounts = discount
        } else {
            let arg1 = Number(payNuber)
            let arg2 = Number(discount)

            function accSubtr(arg1,arg2){
                var r1,r2,m,n;
                try{r1=arg1.toString().split(".")[1].length;}catch(e){r1=0;}
                try{r2=arg2.toString().split(".")[1].length;}catch(e){r2=0;}
                m=Math.pow(10,Math.max(r1,r2));
                //动态控制精度长度
                n=(r1>=r2)?r1:r2;
                return ((arg1*m-arg2*m)/m).toFixed(n);
            } 

            function accMul(arg1,arg2){
                var m=0,s1=arg1.toString(),s2=arg2.toString();
                try{m+=s1.split(".")[1].length}catch(e){};
                try{m+=s2.split(".")[1].length}catch(e){};
                return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
            }

            function accDivCoupon(arg1,arg2){
                var t1=0,t2=0,r1,r2;
                try{t1=arg1.toString().split(".")[1].length;}catch(e){};
                try{t2=arg2.toString().split(".")[1].length;}catch(e){};
                r1=Number(arg1.toString().replace(".",""));
                r2=Number(arg2.toString().replace(".",""));
                return (r1/r2)*Math.pow(10,t2-t1);
            }
            let a  = accDivCoupon(arg2,100);
            let b = accMul(arg1,a)
            discounts = accSubtr(arg1,b)
            payNuber = b
            if(payNuber<=0.01){
                payNuber=0.01
            }
            // discounts = payNuber - (payNuber * (Number(discount) / 100))
            // payNuber = payNuber * (Number(discount) / 100)
        }
        this.setState({
            payMoney: payNuber,
            discountpay: discounts,
            isOpen:false,
            coupons_id:id
        },console.log(this.state.payMoney,this.state.isOpen))
    }

    show() {
        Taro.showModal({
            title: '服务说明',
            content: '支付完成后即可向医生咨询，24小时内不限交流次数,医生收到咨询后会尽快回复咨询，但由于医生工作繁忙，很多时候只能利用工作之外的时间来回复咨询，如特殊原因不能及时回复,请谅解,超过24小时未收到医生回复则系统自动退款',
            showCancel: false,
            confirmColor: '#0000FF'
        })
    }
    offect = 0;
    length = 20;
    total = 0;
    isFinlsh = false;

    //上拉加载
    onReachBottom() {
        if ((this.offect + this.length) < this.total) {
            app.success('正在加载----')
            this.offect = this.offect + this.length;
            this.isFinlsh = false;
            this.getData2();
        } else {
            app.success('没有更多数据了咯')
            this.isFinlsh = true;
        }
    }
    //获取数据
    // 医生
    getData() {
        let me = this
        let data = { doctor_id: this.$router.params.doc_id }
        console.log(data)
        app.post('web/members/doctorHome', data, function (res) {
            let result = res.data.result
           
            for(let i = 0; i< result.labels.length; i++){
                if( result.labels[i] == ''){
                    result.labels.splice(i,1)
                }
            }
             me.setState({
                    docInfo:result
             })
            Taro.setNavigationBarTitle({
                title: res.data.result.name
            });
        })
    }
    // 获取咨询记录
    getData2() {
        let me = this
        let data = { doctor_id: this.$router.params.doc_id, offset: this.offect, length: this.length }
        let dataArr = []
        app.post('web/myself/consultRecord', data, function (res) {
            dataArr = me.state.charArr.concat(res.data.result.list)
            me.total = res.data.result.total
            me.setState({
                charArr: dataArr
            })
        })
    }
    
    // 获取费用信息
    getData4() {
        let me = this
        let data = { doctor_id: this.$router.params.doc_id, type:'专家咨询' }
        app.post('web/myself/onOrderData', data, (res) => {
            me.setState({
                pay: res.data.result,
                payMoney:res.data.result.totpalPrice
            })
        })
    }

    handleClose () {
        this.setState({
            isOpen:false
        })
    }

    componentDidMount() {
        this.getData();
        this.getData2();
        this.getData4();
    }


    render() {
        let paymoney = this.state.payMoney
        let intMoney = Number(paymoney).toFixed(2)
        var tabList2 = [{ title: '在线咨询' }, { title: '咨询记录' }]
        let date = new Date().toLocaleTimeString()
        //顶部医生数据
        let docInfo = this.state.docInfo
        // 医生标签
        let labels = !app.isEmpty(this.state.docInfo.labels) ? this.state.docInfo.labels : [];
        let tags = labels.map((itemtag) => {
            return <View key={itemtag.id}>
                        <AtTag className='tag' circle>
                            {itemtag}
                        </AtTag>
            </View>
        })
        // 咨询记录数据
        let infoList2 
        if(this.state.charArr.length == 0 || this.state.charArr.length == undefined){
            infoList2 = <View className='noRe'>咨询记录为空！</View>
        }else{
            infoList2 = this.state.charArr.map((items) => {
                            return <View onClick={this.gotochatRecord.bind(this, items)} key={items.id}>
                                <View className='tt'>
                                    <View className='title'><Text>{items.patient_name}的咨询</Text></View>
                                    <View><Text>{items.created_at}</Text></View>
                                </View>
                                <View className='tt2'>
                                    <View className='tt2t'><Text>{item.content}</Text></View>
                                    <View><Text>{items.status}</Text></View>
                                </View>
                            </View>
            })
        }
        // 优惠券数据
        //  this.state.pay.coupons.map((item2) => {
        //     if (item2.coupon_type == "满减") {
        //     return <AtListItem title={'￥' + item2.discount} extraText='使用' note={item2.title} onClick={this.youhui.bind(this, item2.discount, item2.coupon_type)}></AtListItem>
        //     } 
        //     return <AtListItem title={item2.discount + '折'} extraText='使用' note={item2.title} onClick={this.youhui.bind(this, item2.discount, item2.coupon_type)}></AtListItem>
        // })
        
        //优惠卷数量不为空
        let couponNum = this.state.pay.coupons.map((item2) => {
                                return <View className='payList' onClick={this.youhui.bind(this,item2.discount,item2.scope,item2.coupon_type,item2.id,item2.full_money,item2.start_time,item2.end_time)}>
                                       <AtListItem key={item2.id}
                                         // title={'￥' + item2.discount}
                                            extraText='使用'
                                            note={item2.title}>
                                        </AtListItem>
                                </View>
                            })

        // 支付金额
        let payMoney = this.state.payMoney

        return (
            <View className='doctorSession'>
                {/* 医生数据 */}
                <View className='docInfo'>
                    <View>
                        <Image
                            className='avider'
                            src={docInfo.head_image}
                        />
                    </View>
                    <View className='infoText'>
                        <View className='textTile'>
                            <View>
                                <Text className='name'>{docInfo.name}</Text>
                                <Text className='t'>{docInfo.positional_title}</Text>
                            </View>
                            <View>
                                <Image className='starStyle' src={star} />
                                <Text className='t5'>{docInfo.general_score}</Text>
                            </View>
                        </View>
                        <View ><Text>{docInfo.hospital}</Text></View>
                        <View className='goodAt'>
                            <Text>擅长：{docInfo.speciality}</Text>
                        </View>
                        <View className={(this.state.docInfo.labels.length == 0 || this.state.docInfo.labels.length == undefined) ? 'noshow' : 'infoTag'}>
                            {tags}
                        </View>
                    </View>
                </View>
                {/* tabPage */}
                <View className='abc'>
                <AtTabs className='tab' current={this.state.currents} tabList={tabList2} onClick={this.handleClicks.bind(this)}>
                    {/* 在线咨询 */}
                    <AtTabsPane current={this.state.currents} index={0}> 
                       
                        <View className='talk'>     
                            <View className='text'><Text>{date}</Text></View>
                            <View className='imageinfo-text' >
                                <View className='imageinfo-text-useravider'>
                                    <Image className='avider' src={docInfo.head_image} />
                                </View>
                               
                                <View className='imageinfo-text--userdir'>
                                    <Text>
                                        你好，我是{docInfo.name}医生，有任何关于眼部健康的问题都欢迎向我咨询，我很乐意为你提供帮助？
                                    </Text>
                                </View>
                            </View>
                        </View>
                    </AtTabsPane>
                    {/* 咨询记录 */}
                    <AtTabsPane current={this.state.currents} index={1}>
                        {infoList2}
                    </AtTabsPane>
                </AtTabs>
                </View>
                
                {/* 底部付费内容区 */}
                <View className='list' style={this.state.currents == 0 ? 'display:block' : 'display:none'}>
                    <View className='list-item' onClick={this.show}>
                        <View className='list-left'>
                            <View className='title'>
                                <Text>服务说明</Text>
                            </View>
                        </View>
                        <View className='list-right'>
                            <Image className='right-icon' src={right} />
                        </View>
                    </View>
                    <View className='list-item'>
                        <View className='list-left'>
                            <View className='title'>
                                <Text>咨询费用</Text>
                            </View>
                        </View>
                        <View className='list-right'>
                            <Text className='t1'>￥{this.state.pay.totpalPrice}元</Text>
                        </View>
                    </View>
                    <View className='list-item'>
                        <View className='list-left'>
                            <View className='title'>
                                <Text>优惠抵扣</Text>
                            </View>
                        </View>
                        <View className='list-right' onClick={this.openFloat.bind(this)}>
                            <Text className='t2'>-￥ {this.state.discountpay}元</Text>
                            <Image className='right-icon' src={right} />
                            <AtFloatLayout isOpened={this.state.isOpen} onClose={this.handleClose.bind(this)}>
                                <AtList hasBorder>
                                    {  
                                        couponNum
                                    }                                            
                                </AtList>
                            </AtFloatLayout>
                        </View>
                    </View>
                    <View className='buttomView'>
                        <View className='button-left'>
                            <Text className='t4'>实际支付</Text>
                            <Text className='t3'>{this.state.payMoney <= 0 ? 0 : intMoney}元</Text>
                        </View>
                        <View className='button-right' onClick={this.gotoQuicklyFoundModify.bind(this)}>
                            <AtButton type='primary' >立即咨询</AtButton>
                        </View>
                    </View>
                </View>
            </View>
        )
    }
}